<template>
  <div>
    <t-form ref="form" :rules="rules" :data="formData" :colon="true" @submit="onSubmit" label-width="0">
      <t-dialog
        header="添加学术研究"
        :visible="props.visible"
        :confirm-on-enter="true"
        :on-cancel="closetable"
        :on-close="closetable"
        :cancelBtn="null"
        :confirmBtn="null"
        :loading="loading"
      >
        <template #body>
          <div class="dialog-box">
            <t-form-item label="" name="name">
              <div class="hw-from-content">
                <div class="from-title-box">
                  <span class="from-title-box-tip">*</span>
                  <span class="from-title-box-name">标题</span>
                </div>
                <t-input
                  @change="namechange"
                  v-model="formData.name"
                  :maxlength="60"
                  placeholder="请输入标题"
                ></t-input>
              </div>
            </t-form-item>
            <div class="content-parent">
              <t-form-item label="" name="typeId">
                <div class="hw-from-content">
                  <div class="from-title-box">
                    <span class="from-title-box-name">类型</span>
                  </div>
                  <t-select placeholder="请选择文章类型" v-model="formData.typeId" style="width: 284px">
                    <t-option
                      v-for="item in props.selectList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.text"
                    ></t-option>
                  </t-select>
                </div>
              </t-form-item>
              <t-form-item label="" name="author">
                <div class="hw-from-content">
                  <div class="from-title-box">
                    <span class="from-title-box-name">作者</span>
                  </div>
                  <t-input
                    style="width: 284px"
                    :maxlength="30"
                    v-model="formData.author"
                    placeholder="请输入作者名称"
                  ></t-input>
                </div>
              </t-form-item>
            </div>
            <div class="content-parent">
              <t-form-item label="" name="publisher">
                <div class="hw-from-content">
                  <div class="from-title-box">
                    <span class="from-title-box-name">来源</span>
                  </div>
                  <t-input
                    :maxlength="50"
                    style="width: 284px"
                    v-model="formData.publisher"
                    placeholder="请输入来源"
                  ></t-input>
                </div>
              </t-form-item>
              <t-form-item label="">
                <div class="hw-from-content">
                  <div class="from-title-box">
                    <span class="from-title-box-name">发表时间</span>
                  </div>
                  <t-input
                    style="width: 284px"
                    :maxlength="30"
                    v-model="formData.PublishedOn"
                    placeholder="请输入发表时间"
                  ></t-input>
                </div>
              </t-form-item>
            </div>
            <t-row :gutter="16">
              <t-col :span="12">
                <span class="from-title">原文链接</span>
                <t-form-item label="原文链接" name="url">
                  <t-input v-model="formData.url" :maxlength="248"></t-input>
                </t-form-item>
              </t-col>
              <!-- <t-col :span="6">
                <span class="from-title">类型</span>
                <t-form-item label="商品名称" name="typeId">
                  <t-select placeholder="请选择文章类型" v-model="formData.typeId">
                    <t-option
                      v-for="item in props.selectList"
                      :key="item.id"
                      :value="item.id"
                      :label="item.text"
                    ></t-option>
                  </t-select>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <span class="from-title">作者</span>
                <t-form-item label="作者" name="author">
                  <t-input v-model="formData.author" placeholder="请输入作者名称"></t-input>
                </t-form-item>
              </t-col> -->
              <!-- <t-col :span="6">
                <span class="from-title">出处/出版社</span>
                <t-form-item label="商品名称" name="publisher">
                  <t-input v-model="formData.publisher" placeholder="请输入出处"></t-input>
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <span class="from-title">发表时间</span> 
                <t-form-item label="发表时间">
                  <t-input v-model="formData.PublishedOn" placeholder="请输入发表时间"></t-input>
                </t-form-item>
              </t-col> -->
              <t-col :span="12">
                <span class="from-title">内容</span>
                <t-form-item label="内容" name="content">
                  <edit v-if="editLock" :Descriptions="formData.content" v-model="formData.content" />
                </t-form-item>
              </t-col>

              <t-col :span="12" class="flex">
                <t-form-item label="项目封面" help="">
                  <div class="hw-from-content">
                    <div class="from-title-box">
                      <span class="from-title-box-name">PDF资源</span>
                    </div>
                    <t-upload
                      v-if="formData.imgList.length < 1"
                      v-loading="pdfLoading"
                      ref="uploadRef1"
                      :allowUploadDuplicateFile="true"
                      :size-limit="{ size: 20, unit: 'MB' }"
                      theme="custom"
                      accept="file_extension/*"
                      :auto-upload="true"
                      :upload-all-files-in-one-request="uploadAllFilesInOneRequest"
                      :before-upload="beforeUpload"
                      @Validate="onValidate"
                    >
                      <div class="upload-box hw-flex-style-c-c">
                        <i class="doorIcon">&#xe657;</i>
                        <span>选择PDF</span>
                      </div>
                    </t-upload>
                    <div class="list-tip-box">
                      <span class="audio-tip">仅支持PDF格式，文件在页面中直接显示，最多可上传一个大小不超过20M</span>
                    </div>
                  </div>
                </t-form-item>
                <researchTable
                  v-if="formData.imgList.length !== 0"
                  :datas="formData.imgList"
                  :columns="uploadColumns"
                  @removeIndex="removeIndex"
                />
              </t-col>
              <t-col :span="12" class="flex">
                <!-- <span class="from-title">其他资源</span> -->
                <t-form-item label="项目封面" help="">
                  <div class="hw-from-content">
                    <div class="from-title-box">
                      <span class="from-title-box-name">其他资源</span>
                    </div>
                    <div>
                      <t-upload
                        v-if="formData.imgList1.length < 3"
                        v-loading="minLoading"
                        ref="uploadRef1"
                        :allowUploadDuplicateFile="true"
                        :size-limit="{ size: 20, unit: 'MB' }"
                        theme="custom"
                        :headers="heards"
                        :before-upload="beforeUpload1"
                        :upload-all-files-in-one-request="uploadAllFilesInOneRequest"
                        @Validate="onValidate"
                      >
                        <div class="upload-box hw-flex-style-c-c">
                          <i class="doorIcon">&#xe657;</i>
                          <span>选择文件</span>
                        </div>
                      </t-upload>
                    </div>
                    <div class="list-tip-box">
                      <span class="audio-tip">观众可自由下载附件资源，最多可上传三个,单个大小不超过20M</span>
                    </div>
                  </div>
                </t-form-item>

                <researchTable
                  v-if="formData.imgList1.length !== 0"
                  :datas="formData.imgList1"
                  :columns="uploadColumns"
                  @removeIndex="removeIndex1"
                />
              </t-col>
            </t-row>
          </div>
        </template>
        <template #footer>
          <t-button @click="closetable" theme="default" variant="outline">取消</t-button>
          <t-button type="submit">确定</t-button>
        </template>
      </t-dialog>
    </t-form>
  </div>
</template>

<script setup lang="ts">
// @ts-nocheck
import { formatFileSize } from '@/utils/minxin';
import { upLoadFn } from '@/utils/request/upload';
import edit from '@/components/RichText/Editor.vue';
import { url, heards, urls } from '@/utils/request/upload';
import { ref, reactive, defineExpose, nextTick } from 'vue';
import researchTable from './researchTable.vue';
import { uploadColumns } from './data';
import { MessagePlugin } from 'tdesign-vue-next';

const props = defineProps({
  visible: {
    type: Boolean,
  },
  info: {
    type: Object,
  },
  selectList: {
    type: Array,
  },
});
const emit = defineEmits(['close', 'submit']);
const uploadAllFilesInOneRequest = ref(false);
const loading = ref(false);
const pdfLoading = ref(false);
const minLoading = ref(false);
const editLock = ref(true);

const formData = reactive({
  id: 0,
  name: '',
  typeId: '',
  author: '',
  publisher: '',
  PublishedOn: '',
  url: '',
  content: '',
  data: [],
  pdfData: [],
  imgList: [],
  imgList1: [],
});
const rules = {
  name: [{ required: true, message: '名称必填', type: 'error' }],
  // typeId: [{ required: true, message: '类型必填', type: 'error' }],
  // author: [{ required: true, message: '作者必填', type: 'error' }],
  // publisher: [{ required: true, message: '来源必填', type: 'error' }],
  // url: [{ required: true, message: '名称必填', type: 'error' }],
  // content: [{ required: true, message: '内容必填', type: 'error' }],
};
const closetable = () => {
  //   visible1.value = false;
  emit('close');
};
const isURL = (input) => {
  // 匹配URL的正则表达式
  var urlPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i;

  // 判断输入是否匹配正则表达式
  return urlPattern.test(input);
};
const namechange = () => {
  //监听空格输入

  formData.name = formData.name.replace(/\s/g, '');
};
const onSubmit = ({ validateResult, firstError }) => {
  if (pdfLoading.value || minLoading.value) {
    MessagePlugin.warning('正在上传中');
    return;
  }

  if (formData.url) {
    let urlType = isURL(formData.url);
    if (!urlType) {
      MessagePlugin.warning('请填写正确链接');
      return;
    }
  }

  if (validateResult === true) {
    // MessagePlugin.success('提交成功');
    emit('submit', formData);
  } else {
    // console.log('Validate Errors: ', firstError, validateResult);
    MessagePlugin.warning(firstError);
  }
};
const onSuccess = (e) => {
  //pdf上传
};
const beforeUpload = (file: any) => {
  //回调钩子
  console.log(file.type);
  if (file.type !== 'application/pdf') {
    MessagePlugin.warning('请选择pdf文件');
    return;
  }
  if (file.size / 1048576 > 20) {
    MessagePlugin.warning('请选择不大于20M的文件上传');
    return;
  }
  pdfLoading.value = true;

  upLoadFn(file, 5).then((res) => {
    // console.log(res);
    if (res) {
      let obj = {
        url: res,
        type: 1,
        name: file.name,
        size: file.size,
        status: 0,
        operation: null,
      };
      formData.imgList.push(obj);
      formData.pdfData.push(obj);
      // formData.coverUrl = res;
    } else {
      MessagePlugin.error('创建成功');
    }
    pdfLoading.value = false;
  });
};
const onValidate = () => {};
const beforeUpload1 = (file: any) => {
  //回调钩子
  if (file.size / 1048576 > 20) {
    MessagePlugin.warning('请选择不大于20M的文件上传');
    return;
  }
  minLoading.value = true;

  upLoadFn(file, 5).then((res) => {
    // console.log(res);
    if (res) {
      let obj = {
        url: res,
        type: 2,
        name: file.name,
        size: file.size,
        status: 0,
        operation: null,
      };
      formData.imgList1.push(obj);
      formData.data.push(obj);
      // formData.coverUrl = res;
    } else {
      MessagePlugin.error('创建成功');
    }
    minLoading.value = false;
  });
};

const removeIndex = (e, url) => {
  formData.imgList.splice(e, 1);
  formData.pdfData[e].status = 2;
  // console.log('删除pdf文件', arr);
  // if (formData.pdfData[arr].id) {
  //   formData.pdfData[arr].status = 2;
  // } else {
  //   // formData.pdfData.splice(arr, 1);
  // }
};
const removeIndex1 = (e, url) => {
  // console.log('删除其他文件');
  formData.imgList1.splice(e, 1);
  formData.data[e].status = 2;
  // let arr = formData.data.findIndex((el) => {
  //   return el.url == url;
  // });
  // if (formData.data[arr]?.id) {
  //   formData.data[arr].status = 2;
  // } else {
  //   // formData.data.splice(arr, 1);
  // }
};
const setdatas = (e) => {
  editLock.value = false;
  formData.id = e.id;
  formData.name = e.name;
  formData.typeId = e.typeId ? e.typeId : '';
  formData.author = e.author;
  formData.publisher = e.publisher;
  formData.url = e.url;
  formData.PublishedOn = e.publishedOn;
  formData.content = e.content;
  formData.data = e.data ? e.data : [];
  formData.pdfData = e.pdfData ? e.pdfData : [];
  let data1 = e.data ? e.data : [];
  let data2 = e.pdfData ? e.pdfData : [];
  formData.imgList1 = [];
  formData.imgList = [];
  data1.forEach((element) => {
    formData.imgList1.push(element);
  });
  data2.forEach((element) => {
    formData.imgList.push(element);
  });
  nextTick(() => {
    editLock.value = true;
  });
};

defineExpose({
  setdatas,
});
</script>

<style lang="less" scoped>
.flex {
  :deep(.t-form__controls) {
    display: flex;
    align-items: center;
  }
  :deep(.t-input__help) {
    margin-left: 20px !important;
    margin-top: 0px;
  }
}
:deep(.t-dialog) {
  height: 60vh;
}
:deep(.t-input--focused) {
  box-shadow: none;
}
.from-title {
  display: flex;
  font-size: 16px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.8);
  line-height: 24px;
  margin-bottom: 8px;
}
.upload-box {
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 124px;
  height: 36px;
  border-radius: 4px;
  border: 1px solid #e62b17;
  .doorIcon {
    color: #e62b17;
    font-size: 16px;
    margin-right: 8px;
  }

  span {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #e62b17;
    line-height: 24px;
  }
}
.upload-box:hover {
  background: #ffece6;
}
:deep(.t-dialog__body) {
  height: calc(60vh - 156px);
  padding: 0 40px;
}
.dialog-box {
  height: 100%;
  overflow: scroll;
  scrollbar-width: none;
}
.dialog-box::-webkit-scrollbar {
  display: none;
}
.t-row {
  margin-top: 0;
}
.t-col {
  margin-bottom: 24px;
}
:deep(.t-table) {
  border: 1px solid #e7e7e7;
  border-bottom: none;
}
.research-box::-webkit-scrollbar {
  display: none;
}
.content-parent {
  display: flex;
  justify-content: space-between;
  width: 584px;
}
.audio-tip {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.38);
  line-height: 22px;
  margin-top: 8px;
}
</style>
